// pages/shoppage/shoppage.js
var COS = require('../../libs/cos-wx-sdk-v5');
var wxfs = wx.getFileSystemManager();
var config = require('../../config');
var cos = new COS({
  SecretId: 'AKIDrT55qKQZw4OSb6me3KvG9nBKCpAJJG9S',
  SecretKey: 'OXieKlxvd5OSI5ewzl24h41Z3rPT7WfY',
});
var TaskId;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //被选中的图片路径
    chooseImgs: []
  },
  //外网图片的路径数组
  UpLoadImgs: [],
  //点击加号选择图片
  handleChooseImg() {
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (result) => {
        console.log(result)
        this.setData({
          //图片数组拼接
          chooseImgs: [...this.data.chooseImgs, ...result.tempFilePaths]
        })
      },
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  //点击图片删除
  handleRemoveImg(e) {
    const {
      index
    } = e.currentTarget.dataset;
    console.log(index);
    let {
      chooseImgs
    } = this.data
    chooseImgs.splice(index, 1);
    this.setData({
      chooseImgs
    })
  },

  //提交按钮的点击事件
  handleFormSubmit() {
    const {
      chooseImgs
    } = this.data
    //合法性验证
    /*
    if (!shuju.trim()) {
      wx.showToast({
        title: '输入不合法',
        icon:'none',
        mask: true,
      });
      return;
    }
    */
   wx.showLoading({
     title: '正在上传中',
     mask:'true'
   })
    //不支持多个文件同时上传
    chooseImgs.forEach((v, i) => {
      //微信对路径进行了处理 for examlpe'http://tmp/rXyXBWjCIlJlf3889fbc5953fbaa8a78745d64e917a5.png'
      console.log(v)
      cos.postObject({
        Bucket: config.Bucket,
        Region: config.Region,
        //图片路径去掉 http://tmp/
        Key: `${v.slice(11)}`,
        FilePath: v,
        onTaskReady: function (taskId) {
          TaskId = taskId
        },
        onProgress: function (info) {
          //console.log(JSON.stringify(info));
        }
      }, (err, data) =>{
        console.log(err || data);
        if (err && err.error) {
          console.log('请求失败：'+err.error.Message || err.error)
          console.log('状态码：' + err.statusCode,)
        } else if (err) {
          console.log('请求出错：' + err)
          console.log('状态码：' + err.statusCode)
        } else {
          this.UpLoadImgs.push('https://'+data.Location);
        }
        if(i==chooseImgs.length-1){
          wx.hideLoading()
          console.log('打印本地外网图片地址')
          console.log(this.UpLoadImgs)
          this.setData({
            chooseImgs:[]
          })
        }
      });
    })
  }
})